package com.sanerzone.smscenter.biz.listener;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.common.support.utils.FstObjectSerializeUtil;
import com.sanerzone.smscenter.biz.cache.AccountCacheHelper;
import com.sanerzone.smscenter.biz.entity.SmsSend;
import com.sanerzone.smscenter.biz.mapper.SmsSendMapper;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSQMessage;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.common.tools.JedisUtils;
import net.sf.ehcache.transaction.xa.EhcacheXAException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SMSRCListener implements MessageListenerConcurrently {
    public static Logger logger = LoggerFactory.getLogger(SMSRCListener.class);
    @Autowired
    private SmsSendMapper smsSendMapper;

    public static String getTableIndex(String bizid) {
        if (StringUtils.isNotBlank(bizid)) {
            return String.valueOf(new MsgId(bizid).getDay());
        } else {
            return "";
        }
    }

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        try {
            for (MessageExt msg : msgs){
                SMSSQMessage smssqMessage = (SMSSQMessage) FstObjectSerializeUtil.read(msg.getBody());

                Map map=new HashMap( );

                map.put( "submitId",smssqMessage.getSubmitId() );
                map.put( "taskId",smssqMessage.getTaskId() );
                map.put( "submitTime",smssqMessage.getSubmitTime());
                map.put( "userId",smssqMessage.getUserId() );
                map.put( "content",smssqMessage.getContent() );
                map.put( "count",smssqMessage.getCount() );
                int res=smsSendMapper.insertSubmitAction( map );
                if (res==1){
                    logger.info( "用户userId:{}保存提交动作成功。taskIds:{}",smssqMessage.getUserId(),smssqMessage.getTaskId() );
                }else{
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
            }catch (Exception e){
            e.printStackTrace();
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
